<?php $this->headTitle('Sale');  ?>
<?php $this->headScript()->appendFile('js/jquery/tab.js'); ?>

<?php if(!empty($this->returnMessageSuccess)): ?>
<div class="success"><?php echo $this->escape($this->returnMessageSuccess[0]); ?></div>
<?php endif; ?>

<?php if(!empty($this->returnMessageWarning)): ?>
<div class="warning"><?php echo $this->escape($this->returnMessageWarning[0]); ?></div>
<?php endif; ?>

<div class="box">
  <div class="left"></div>
  <div class="right"></div>
  <div class="heading">
    <h1 style="background-image: url('images/order.png');">Sale</h1>
    <div class="buttons">
    <a class="button" id="saleBtn"><span>Sale</span></a>
    <a onclick="location = '<?php echo $this->backUrl; ?>';" class="button"><span><< Back</span></a>
    </div>
    </div>
  <div class="content">
  <div style="display: inline-block; width: 100%;">
  <div class="vtabs">
      <a tab="#tab_product">Products</a>
      <a tab="#tab_customer">Customer Information</a>
  </div>
      <form action="<?php echo $this->formAction; ?>" method="post" enctype="multipart/form-data" id="form" autocomplete="off">
	  <input type="hidden" name="sale[saleId]" value="<?php if(isset($this->sale['saleId'])): ?><?php echo $this->sale['saleId']; ?><?php endif; ?>">
        
        <div id="tab_product" class="vtabs_page">
        <table id="products" class="list">
          <thead>
            <tr>
              <td class="left">Product</td>
              <td class="right">Quantity</td>

              <td class="right">Unit Price</td>
              <td class="right" width="1">Total</td>
            </tr>
          </thead>

          <?php if(!empty($this->product)): ?>
          <?php $productRow = 1; ?>
            <?php foreach($this->product as $productInfo): ?>
                  <tbody id="product_<?php echo $productRow; ?>">
                  <tr>
	          <td class="left">
	          <input type="hidden" name="product[<?php echo $productRow; ?>][productId]" value="<?php echo $productInfo['productId']; ?>">
                  <input type="hidden" name="product[<?php echo $productRow; ?>][name]" value="<?php echo $this->escape($productInfo['name']); ?>">
	          <span onclick="$('#product_<?php echo $productRow; ?>').remove();" class="remove">&nbsp;</span>
	          <a target="_blank" href="<?php echo $this->url(array('do'=>'update','id'=>$productInfo['productId']),'catalogProduct',true); ?>"><?php echo $this->escape($productInfo['name']); ?></a>
                  </td>
                  <td class="right"><input type="text" name="product[<?php echo $productRow; ?>][quantity]" value="<?php echo $productInfo['quantity']; ?>" size="4" class="product_<?php echo $productRow; ?>" id="product_<?php echo $productRow; ?>_quantity" onkeydown="calculateTotal(this);" onkeyup="calculateTotal(this);"/></td>
	          <td class="right"><input type="text" name="product[<?php echo $productRow; ?>][unitPrice]" value="<?php echo $productInfo['unitPrice']; ?>" readonly="readonly" class="product_<?php echo $productRow; ?>" id="product_<?php echo $productRow; ?>_price" /></td>
	          <td class="right"><input type="text" name="product[<?php echo $productRow; ?>][total]" value="<?php echo $productInfo['total']; ?>" readonly="readonly" class="product_<?php echo $productRow; ?>" id="product_<?php echo $productRow; ?>_total" /></td>
	          </tr>
	          </tbody>
            <?php $productRow++; ?>
            <?php endforeach; ?>
            <?php endif; ?>

          <tbody id="totalTable">
            <tr>
              <td colspan="3" class="right"><span style="text-align:right;">Total:</span></td>
              <td class="right"><input type="text" name="sale[total]" id="total" value="<?php echo $this->sale['total']; ?>" readonly="readonly" /></td>
            </tr>
         </tbody>
         
        </table>

            <br/> <br/>
            
                 <table>
                    <tr>
		    <td><br/> Add Product(s):<br/>
		      <table>
			    <tr>
			      <td style="padding: 0;" colspan="3"><select id="category" style="margin-bottom: 5px;" onchange="getProducts();">
                                                                 <?php foreach($this->categories as $category): ?>
                                                                <option value="<?php echo $category['categoryId']; ?>"><?php echo $this->escape($category['name']); ?></option>
                                                                 <?php endforeach; ?>
			        			        </select></td>
			    </tr>
			    <tr>
			      <td style="padding: 0;">
			        <select multiple="multiple" id="product" size="10" style="width: 350px;">
			        </select>

			      </td>
			      <td style="vertical-align: middle;"><span class="add" onclick="addProduct();">&nbsp;</span></td>
			    </tr>
		    </table>
		  </tr>
		</table>
      </div>
       
      <div id="tab_customer" class="vtabs_page">
        <table class="form">
          <tr>
            <td><span class="required">*</span>Customer Name:</td>
            <td><input type="text" name="sale[customerName]" value="<?php echo $this->sale['customerName']; ?>" id="customerName" /></td>
          </tr>
          <tr>
            <td>Customer Address:</td>
            <td><textarea name="sale[customerAddress]" id="customerAddress" rows="5" cols="50"><?php echo $this->sale['customerAddress']; ?></textarea></td>
          </tr>
          <tr>
            <td><span class="required">*</span>Telephone:</td>
            <td><input type="text" name="sale[customerPhone]" value="<?php echo $this->sale['customerPhone']; ?>" id="customerPhone" /></td>
          </tr>
        </table>
      </div>

      </form>

  </div>
</div>
</div>
<script type="text/javascript"><!--

var productRow = <?php echo $value = (isset($productRow)) ? $productRow : 1; ?>;

function addProduct() {

	$('#product :selected').each(function() {

            $.ajax({
		url: 'ajax/product/' + $(this).val(),
		dataType: 'json',
		success: function(data) {
			addProductRow(data);
		}
            });

	});
}

function addProductRow(productInfo) {

        html  = '<tbody id="product_' + productRow + '">';
        html += '<tr>';
	    html += '<td class="left">';
	    html += '<input type="hidden" name="product[' + productRow + '][productId]" value="' + productInfo.productId + '">';
        html += '<input type="hidden" name="product[' + productRow + '][name]" value="' + productInfo.name + '">';
	    html += '<span onclick="$(\'#product_' + productRow + '\').remove();" class="remove">&nbsp;</span>';
	    html += '<a target="_blank" href="catalog/product/update/' + productInfo.productId + '">' + productInfo.name + '</a>';
	    html += '</td>';
        html += '<td class="right"><input type="text" name="product[' + productRow + '][quantity]" value="" size="4" class="product_' + productRow + '" id="product_' + productRow + '_quantity" onkeydown="calculateTotal(this);" onkeyup="calculateTotal(this);"/></td>';
	    html += '<td class="right"><input type="text" name="product[' + productRow + '][unitPrice]" value="" class="product_' + productRow + '" id="product_' + productRow + '_price" onkeydown="calculateTotal(this);" onkeyup="calculateTotal(this);"/></td>';
	    html += '<td class="right"><input type="text" name="product[' + productRow + '][total]" value="" readonly="readonly" class="product_' + productRow + '" id="product_' + productRow + '_total" /></td>';
	    html += '</tr>';
	    html += '</tbody>';

	    $('#totalTable').before(html);
            
	    productRow++;

}
//--></script>

<script type="text/javascript"><!--
function getProducts() {

	$('#product option').remove();

	$.ajax({
		url: 'ajax/products/' + $('#category').val(),
		dataType: 'json',
		success: function(data) {
			for (i = 0; i < data.length; i++) {
	 			$('#product').append('<option value="' + data[i]['productId'] + '">' + data[i]['name'] + '</option>');
			}
		}
	});
}

getProducts();
//--></script>

<script type="text/javascript">

$(document).ready(function(){

    // Confirm Allocate
    $('#saleBtn').click(function(){

            valuesOk = false;

		$("input[name*=\'quantity\']").each(function(i,e){
			if(($.trim($(this).val()) == "") || (Number($(this).val()) <= 0) || (isNaN(Number($(this).val())))){
				alert("Please enter quantity.");
                                $(this).focus();
                                valuesOk = false;
                                return false;
				}else{
                                    valuesOk = true;
                                }
			});

                        if(valuesOk){

                         if($.trim($('#customerName').val()) == ""){
                                    alert("Please enter customer name.");
                                    $('#customerName').focus();
                                    valuesOk = false;
                                    return false;
                                    }else{
                                        valuesOk = true;
                                    }
                                    
                         if($.trim($('#customerPhone').val()) == ""){
                                    alert("Please enter customer phone number.");
                                    $('#customerPhone').focus();
                                    valuesOk = false;
                                    return false;
                                    }else{
                                        valuesOk = true;
                                    }
                  }

                        if(valuesOk){
                            if (confirm ('Confirm?')) {
                                            $('#form').submit();
                                }
                        }

    });

});
</script>

<script type="text/javascript"><!--
function calculateTotal(element) {
        
        elementClass = $(element).attr("class");

        quantityElement = '#' + elementClass + '_quantity';
        priceElement = '#' + elementClass + '_price';
        productTotalElement = '#' + elementClass + '_total';

        if((isNaN(Number($(quantityElement).val()))) || (Number($(quantityElement).val()) < 0)){
            quantity = 0;
        }else{
        	quantity = Number($(quantityElement).val());
        }

        if((isNaN(Number($(priceElement).val()))) || (Number($(priceElement).val()) < 0)){
        	price = 0;
        }else{
        	price = $(priceElement).val();
        }
        
        productTotal = quantity * price

	$(productTotalElement).val(productTotal);

        totals = 0;
        $("input[id*=\'_total']").each(function(i,e){
			if(($.trim($(this).val()) == "") || (Number($(this).val()) <= 0) || (isNaN(Number($(this).val())))){
				totals = totals + 0;
				}else{
                                    totals = totals + Number($(this).val());
                                }
			});
      $('#total').val(totals);    
}

//--></script>

<script type="text/javascript"><!--
$.tabs('.vtabs a');
//--></script>
